//
//  KABCosplayDetailVC.m
//  kabu
//
//  Created by XiangDongMBP on 2017/2/8.
//  Copyright © 2017年 East. All rights reserved.
//

#import "KABCosplayDetailVC.h"
#import "KABCosDetailTCell.h"
#import <UINavigationBar+Awesome.h>
#import "GlobalHeader.h"
#import "UIColor+XDHex.h"
#import "KABCosDetComTCell.h"
#import "KABCosDetailHeaderHFView.h"
#import "KABCosDetComHeaderHFView.h"
#import "XDAFNetworking.h"
#import "ApiManager.h"
#import "MBProgressHUD+XDPrompt.h"
#import "KABModel.h"
#import <MJRefresh.h>
#import "KABHomepageVC.h"
#import "SZTextView.h"
#import "XDInputView.h"
#import <YYWebImage.h>
#import "NSString+XDNSDate.h"
#import "KABCosplayReplyVC.h"
#import "KSPhotoBrowser.h"
#import "TTTAttributedLabel.h"
#import "KABMineColCosVC.h"
#import "ThemeManager.h"
#import "KABCosReportVC.h"
#import "NSString+XDQiniu.h"

@interface KABCosplayDetailVC ()<UITableViewDelegate, UITableViewDataSource, UIScrollViewDelegate, KABCosDetailTCellDelegate, KABCosDetComTCellDelegate, UITextViewDelegate, KABCosDetailHeaderHFViewDelegate>

@property (strong, nonatomic) IBOutlet UIView *headerView;
@property (weak, nonatomic) IBOutlet UIImageView *headerBgImgView;
@property (weak, nonatomic) IBOutlet UIImageView *headerPortraitImgView;
@property (weak, nonatomic) IBOutlet UILabel *headerNameLabel;
@property (weak, nonatomic) IBOutlet UILabel *headerTimeLabel;
@property (weak, nonatomic) IBOutlet UIButton *headerFollowBtn;
@property (weak, nonatomic) IBOutlet UILabel *headerSignLabel;
@property (weak, nonatomic) IBOutlet UIButton *headerVoteBtn;
@property (weak, nonatomic) IBOutlet UIView *headerRankBgView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *headerRankBgViewHeight;
@property (weak, nonatomic) IBOutlet UILabel *headerRankLabel;
@property (weak, nonatomic) IBOutlet UILabel *headerTicketCntLabel;

@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property (weak, nonatomic) IBOutlet UIView *bottomBgView;
@property (weak, nonatomic) IBOutlet UIButton *bPraiseBtn;
@property (weak, nonatomic) IBOutlet UIButton *bCommentBtn;
@property (weak, nonatomic) IBOutlet UIButton *bCollectBtn;

@property (strong, nonatomic) MJRefreshAutoNormalFooter *mj_footer;

@property (strong, nonatomic) KABCosplayDetail *cosDetail;

@end

static NSString *const kReuseCellId = @"KABCosDetailTCell";
static NSString *const kCommentCellId = @"KABCosDetComTCell";
static NSString *const kDetailHeaderViewId = @"KABCosDetailHeaderHFView";
static NSString *const kDetComHeaderViewId = @"KABCosDetComHeaderHFView";
static NSInteger const kRequestCommentSize = 20;

@implementation KABCosplayDetailVC

#pragma mark - life cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self initNavigationBar];
    [self initSubViews];
}

- (BOOL)hidesBottomBarWhenPushed {
    return YES;
}

- (void)initNavigationBar {
    self.navigationItem.title = self.cosItem.publisher;
    self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStylePlain target:nil action:nil];

    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"cosplay_report"] style:UIBarButtonItemStylePlain target:self action:@selector(reportBarBtnTapped:)];
//    [self.navigationController.navigationBar lt_setBackgroundColor:[UIColor clearColor]];
    if (self.showCloseBtnFlag) {
        self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"关闭" style:UIBarButtonItemStylePlain target:self action:@selector(closeBarBtnTapped:)];
    }
}

- (void)initSubViews {
    self.automaticallyAdjustsScrollViewInsets = NO;
    
//    // 滚动背景隐藏键盘
//    UIScrollView *scrollView = (UIScrollView *)self.view;
//    scrollView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
//    scrollView.delegate = self;
//    
//    self.tableViewWidthConstraint.constant = CGRectGetWidth([UIScreen mainScreen].bounds);
//    self.tableViewHeightConstraint.constant = CGRectGetHeight([UIScreen mainScreen].bounds);
    
//    self.headerBgImgView.image = [[ThemeManager sharedManager] themeImageWithName:@"cosplay_header_bg"];
    
    self.headerPortraitImgView.layer.masksToBounds = YES;
    self.headerPortraitImgView.layer.borderColor = [UIColor whiteColor].CGColor;
    self.headerPortraitImgView.layer.cornerRadius = CGRectGetWidth(self.headerPortraitImgView.bounds) / 2.0;
    self.headerPortraitImgView.layer.borderWidth = 2;
    
    [self.headerPortraitImgView yy_setImageWithURL:[NSURL URLWithString:self.cosItem.publisher_imageurl] placeholder:[KABDefaultVarModel sharedInstance].bigDefaultImg options:YYWebImageOptionSetImageWithFadeAnimation completion:nil];
    
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(headerPortraitImgViewTapped:)];
    [self.headerPortraitImgView addGestureRecognizer:tapGesture];
    
    self.headerNameLabel.text = self.cosItem.publisher;
    self.headerTimeLabel.text = [self.cosItem.publish_time xd_yyyyMMddHHmmssStrToFriendDateStr];
    
    self.headerFollowBtn.layer.masksToBounds = YES;
    self.headerFollowBtn.layer.cornerRadius = CGRectGetHeight(self.headerFollowBtn.bounds) / 2.0;
    self.headerFollowBtn.layer.borderWidth = 1;
    self.headerFollowBtn.layer.borderColor = [UIColor xd_colorWithHex:KABGlobalColorTabBarItemColor].CGColor;
    self.headerFollowBtn.selected = (self.cosItem.follow_state & 0x01);
    self.headerFollowBtn.backgroundColor = self.headerFollowBtn.selected ? [UIColor whiteColor] : [UIColor xd_colorWithHex:KABGlobalColorTabBarItemColor];
    [self.headerFollowBtn addTarget:self action:@selector(headerFollowBtnTapped:) forControlEvents:UIControlEventTouchUpInside];
    
    self.headerVoteBtn.hidden = YES;
    self.headerVoteBtn.layer.masksToBounds = YES;
    self.headerVoteBtn.layer.cornerRadius = CGRectGetHeight(self.headerVoteBtn.bounds) / 2.0;
    [self.headerVoteBtn addTarget:self action:@selector(headerVoteBtnTapped:) forControlEvents:UIControlEventTouchUpInside];
    self.headerRankBgView.hidden = YES;
    
    self.tableView.contentInset = UIEdgeInsetsMake(0, 0, 62.0, 0);
    self.tableView.scrollIndicatorInsets = UIEdgeInsetsMake(0, 0, 62.0, 0);
    CGFloat width = CGRectGetWidth([UIScreen mainScreen].bounds);
    CGFloat height = width * 153.0 / 375.0 + 177.0;
    self.headerView.frame = CGRectMake(0, 0, width, height);
    self.tableView.tableHeaderView = self.headerView;
    
    UINib *detailHNib = [UINib nibWithNibName:kDetailHeaderViewId bundle:nil];
    [self.tableView registerNib:detailHNib forHeaderFooterViewReuseIdentifier:kDetailHeaderViewId];
    UINib *cellNib = [UINib nibWithNibName:kReuseCellId bundle:nil];
    [self.tableView registerNib:cellNib forCellReuseIdentifier:kReuseCellId];
    UINib *comHNib = [UINib nibWithNibName:kDetComHeaderViewId bundle:nil];
    [self.tableView registerNib:comHNib forHeaderFooterViewReuseIdentifier:kDetComHeaderViewId];
    UINib *commentNib = [UINib nibWithNibName:kCommentCellId bundle:nil];
    [self.tableView registerNib:commentNib forCellReuseIdentifier:kCommentCellId];
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.estimatedRowHeight = 400.0;
    self.tableView.sectionHeaderHeight = UITableViewAutomaticDimension;
    self.tableView.estimatedSectionHeaderHeight = 48.0;
//    self.tableView.sectionFooterHeight = UITableViewAutomaticDimension;
//    self.tableView.estimatedSectionFooterHeight = 44.0;
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    // 下拉刷新
    self.tableView.mj_footer = self.mj_footer;
    
    self.bPraiseBtn.layer.masksToBounds = YES;
    self.bPraiseBtn.layer.cornerRadius = CGRectGetWidth(self.bPraiseBtn.bounds) / 2.0;
    self.bCommentBtn.layer.masksToBounds = YES;
    self.bCommentBtn.layer.cornerRadius = CGRectGetWidth(self.bCommentBtn.bounds) / 2.0;
    self.bCollectBtn.layer.masksToBounds = YES;
    self.bCollectBtn.layer.cornerRadius = CGRectGetWidth(self.bCollectBtn.bounds) / 2.0;
    [self.bPraiseBtn addTarget:self action:@selector(bPraiseBtnTapped:) forControlEvents:UIControlEventTouchUpInside];
    [self.bCommentBtn addTarget:self action:@selector(bCommentBtnTapped:) forControlEvents:UIControlEventTouchUpInside];
    [self.bCollectBtn addTarget:self action:@selector(bCollectBtnTapped:) forControlEvents:UIControlEventTouchUpInside];
    
    [self requestCosplayDetail];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.tableView.delegate = self;
    [self scrollViewDidScroll:self.tableView];
    [self.navigationController.navigationBar setShadowImage:[UIImage new]];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    self.tableView.delegate = nil;
    [self.navigationController.navigationBar lt_reset];
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return self.cosDetail.cosplay_detail.count;
    }
    
    return self.cosDetail.comment.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        KABCosDetailTCell *cell = [tableView dequeueReusableCellWithIdentifier:kReuseCellId forIndexPath:indexPath];
        if (indexPath.row < self.cosDetail.cosplay_detail.count) {
//            [cell configViewWithCosDetPubItem:self.cosDetail.cosplay_detail[indexPath.row] loadImage:!self.scrollToComment];
            [cell configViewWithCosDetPubItem:self.cosDetail.cosplay_detail[indexPath.row] loadImage:YES];
        }
        cell.delegate = self;
        return cell;
    } else {
        KABCosDetComTCell *cell = [tableView dequeueReusableCellWithIdentifier:kCommentCellId forIndexPath:indexPath];
        if (indexPath.row < self.cosDetail.comment.count) {
            [cell configViewWithCosDetComItem:self.cosDetail.comment[indexPath.row]];
        }
        cell.delegate = self;
        return cell;
    }
}

#pragma mark - UITableViewDelegate
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        KABCosDetailHeaderHFView *view = [tableView dequeueReusableHeaderFooterViewWithIdentifier:kDetailHeaderViewId];
        view.titleLabel.text = self.cosDetail.topContentLinkAStr;
        view.delegate = self;
        return view;
    } else if (section == 1) {
        KABCosDetComHeaderHFView *view = [tableView dequeueReusableHeaderFooterViewWithIdentifier:kDetComHeaderViewId];
        view.titleLabel.text = [NSString stringWithFormat:@"最新评论(%zd)", self.cosDetail.total_comment];
        return view;
    }
    return nil;
}

//- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
//    return nil;
//}

//- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
//    return 0.1;
//}
//
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 6.0;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (indexPath.section == 0) {
        ;
    } else if (indexPath.section == 1) {
        [self commentTapped:self.cosDetail.comment[indexPath.row]];
    }
}

#pragma mark - KABCosDetailHeaderHFViewDelegate
- (void)kABCosDetailHeaderHFView:(KABCosDetailHeaderHFView *)view linkTapped:(NSURL *)url {
    if ([url isKindOfClass:[NSURL class]]) {
        NSInteger index = [url.absoluteString integerValue];
        NSArray *linkStrArray = self.cosDetail.topContentTopicAndAtUserArray;
        if (index < linkStrArray.count) {
            NSString *linkStr = linkStrArray[index];
            if (linkStr.length <= 2) {
                return;
            }
            if ([linkStr hasPrefix:@"#"]) {
                KABMineColCosVC *vc = [[KABMineColCosVC alloc] init];
                vc.viewType = KABMineColCosVCTypeTopicList;
                vc.topicStr = [linkStr substringWithRange:NSMakeRange(1, linkStr.length - 2)];
                [self showViewController:vc sender:nil];
            } else if([linkStr hasPrefix:@"@"]) {
                KABHomepageVC *vc = [[KABHomepageVC alloc] init];
                vc.user_name = [linkStr substringWithRange:NSMakeRange(1, linkStr.length - 2)];
                [self showViewController:vc sender:nil];
            }
        }
    }
}

#pragma mark - KABCosDetailTCellDelegate
- (void)kABCosDetailTCell:(KABCosDetailTCell *)cell imgViewDownload:(UIImageView *)imgView {
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
//    NSLog(@"加载图片的位置%@, cell = %@", indexPath, cell);
    if (indexPath) {
        [self.tableView reloadData];
//        [self.tableView beginUpdates];
//        [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
//        [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
//        [self.tableView endUpdates];
    }
}
- (void)kABCosDetailTCell:(KABCosDetailTCell *)cell imgViewTapped:(UIImageView *)imgView {
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    
    NSMutableArray *mArray = [NSMutableArray arrayWithCapacity:self.cosDetail.cosplay_detail.count];
    for (KABCosDetPubItem *item in self.cosDetail.cosplay_detail) {
        NSString *thumbImgUrl = [item.image_url xd_qiniuImgUrlWithMaxWidth:CGRectGetWidth([UIScreen mainScreen].bounds)];
        KSPhotoItem *photoItem = [KSPhotoItem itemWithSourceView:imgView
                                                      thumbImage:[KABDefaultVarModel sharedInstance].bigDefaultImg
                                                        imageUrl:[NSURL URLWithString:thumbImgUrl]
                                                originalImageUrl:[NSURL URLWithString:item.image_url]];
        // 这里判断是否加载原图
        YYWebImageManager *manager = [YYWebImageManager sharedManager];
        NSString *key = [manager cacheKeyForURL:[NSURL URLWithString:item.image_url]];
        photoItem.loadOriginalUrl = [manager.cache containsImageForKey:key withType:YYImageCacheTypeMemory];
        
        [mArray addObject:photoItem];
    }
    KSPhotoBrowser *browser = [KSPhotoBrowser browserWithPhotoItems:mArray selectedIndex:indexPath.row];
    browser.dismissalStyle = KSPhotoBrowserInteractiveDismissalStyleScale;
    browser.backgroundStyle = KSPhotoBrowserBackgroundStyleBlur;
    browser.loadingStyle = KSPhotoBrowserImageLoadingStyleDeterminate;
    browser.pageindicatorStyle = KSPhotoBrowserPageIndicatorStyleDot;
    browser.bounces = NO;
    [browser showFromViewController:self];
}

#pragma mark - KABCosDetComTCellDelegate
- (void)kABCosDetComTCell:(KABCosDetComTCell *)cell portraitImgViewTapped:(UIImageView *)imgView {
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    KABCosDetComItem *item = self.cosDetail.comment[indexPath.row];
    
    KABHomepageVC *vc = [[KABHomepageVC alloc] init];
    vc.user_id = item.commentator_id;
    vc.user_name = item.commentator;
    [self showViewController:vc sender:nil];
}
- (void)kABCosDetComTCell:(KABCosDetComTCell *)cell nickNameTapped:(NSURL *)url {
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    KABCosDetComItem *item = self.cosDetail.comment[indexPath.row];
    
    if ([url isKindOfClass:[NSURL class]]) {
        NSInteger userId = [url.absoluteString integerValue];
        KABHomepageVC *vc = [[KABHomepageVC alloc] init];
        vc.user_id = userId;
        vc.user_name = (item.commentator_id == userId) ? item.commentator : item.reply_which_nick_name;
        [self showViewController:vc sender:nil];
    }
}

#pragma mark - UIScrollViewDelegate
#define NAVBAR_CHANGE_POINT 25
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    //    UIColor * color = [UIColor colorWithRed:0/255.0 green:175/255.0 blue:240/255.0 alpha:1];
//    UIColor *color = [UIColor blackColor];
    UIColor *color = [[ThemeManager sharedManager] themeColorWithName:ThemeManagerNavBgColor];
    CGFloat offsetY = scrollView.contentOffset.y;
    if (offsetY > NAVBAR_CHANGE_POINT) {
        CGFloat alpha = MIN(1, 1 - ((NAVBAR_CHANGE_POINT + 64 - offsetY) / 64));
        [self.navigationController.navigationBar lt_setBackgroundColor:[color colorWithAlphaComponent:alpha]];
    } else {
        [self.navigationController.navigationBar lt_setBackgroundColor:[color colorWithAlphaComponent:0]];
    }
}

//- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
//    if (self.scrollToComment == YES) {
//        self.scrollToComment = NO;
//        [self.tableView reloadData];
//    }
//}

#pragma mark - event response
- (void)reportBarBtnTapped:(UIBarButtonItem *)item {
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    [alertVC addAction:[UIAlertAction actionWithTitle:@"举报" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self reportComment:nil OrCosplay:self.cosDetail];
    }]];
    [alertVC addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:nil]];
    [self presentViewController:alertVC animated:YES completion:nil];
}

- (void)headerPortraitImgViewTapped:(UIGestureRecognizer *)gesture {
    KABHomepageVC *vc = [[KABHomepageVC alloc] init];
    vc.user_id = self.cosDetail.publisher_id;
    [self showViewController:vc sender:nil];
}

- (void)headerFollowBtnTapped:(UIButton *)btn {
    if (!self.cosDetail) {
        return;
    }
    BOOL is_follow = (self.cosDetail.follow_state & 0x01);
    [self requestFollowWithFollowerId:self.cosDetail.publisher_id isFollow:!is_follow];
}
- (void)headerVoteBtnTapped:(UIButton *)btn {
    // 这里对是否投票进行判断
    if (self.cosDetail.vote_info.is_vote) {
        return;
    }
    
    [self requestCosplayVote];
}
- (void)bPraiseBtnTapped:(UIButton *)btn {
    self.cosItem.is_praise = !self.cosItem.is_praise;
    self.cosDetail.is_praise = !self.cosDetail.is_praise;
    btn.selected = self.cosDetail.is_praise;
    
    [self requestCosPraiseWithCosId:self.cosDetail.cosplayId isPraise:self.cosDetail.is_praise];
}
- (void)bCommentBtnTapped:(UIButton *)btn {
    [self commentToSomeOne:nil];
}
- (void)bCollectBtnTapped:(UIButton *)btn {
    self.cosItem.is_collected = !self.cosItem.is_collected;
    self.cosDetail.is_collected = !self.cosDetail.is_collected;
    btn.selected = self.cosDetail.is_collected;
    
    [self requestCosCollectWithCosId:self.cosDetail.cosplayId isCollected:self.cosDetail.is_collected];
}
- (void)closeBarBtnTapped:(UIBarButtonItem *)item {
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - private methods
- (void)commentTapped:(KABCosDetComItem *)item {
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    [alertVC addAction:[UIAlertAction actionWithTitle:@"回复" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self commentToSomeOne:item];
    }]];
    [alertVC addAction:[UIAlertAction actionWithTitle:@"举报" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self reportComment:item OrCosplay:nil];
    }]];
    [alertVC addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:nil]];
    [self presentViewController:alertVC animated:YES completion:nil];
}

- (void)reportComment:(KABCosDetComItem *)item OrCosplay:(KABCosplayDetail *)cosDetail {
    KABCosReportVC *vc = [[KABCosReportVC alloc] init];
    vc.cosplayId = cosDetail.cosplayId;
    vc.commentId = item.commentId;
    [self showViewController:vc sender:nil];
}

- (void)commentToSomeOne:(KABCosDetComItem *)item {
    NSInteger toCommentId = -1;
    NSString *placeHolder = @"输入评论";
    if (item) {
        toCommentId = item.commentId;
        placeHolder = [NSString stringWithFormat:@"回复：%@", item.commentator];
    }
    KABCosplayReplyVC *vc = [[KABCosplayReplyVC alloc] init];
    vc.modalPresentationStyle = UIModalPresentationOverCurrentContext;
    vc.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    vc.maxStrLength = KABGlobalCosCommentLenght;
    vc.placeHolder = placeHolder;
    vc.completeHandle = ^(NSString *str) {
        if (str.length) {
            [self requestPublishCommentWithCosId:self.cosDetail.cosplayId content:str replayWhichId:toCommentId];
        }
    };
    [self presentViewController:vc animated:YES completion:nil];
}
- (void)refreshWholeView {
    // 尾部加载更多的显示
    if (self.cosDetail.totalLoad) {
        [self.tableView.mj_footer endRefreshingWithNoMoreData];
    } else {
        [self.tableView.mj_footer resetNoMoreData];
    }
    
    if (!self.cosItem) {
        [self.headerPortraitImgView yy_setImageWithURL:[NSURL URLWithString:self.cosDetail.publisher_imageurl] placeholder:[KABDefaultVarModel sharedInstance].smallDefaultImg];
        self.headerNameLabel.text = self.cosDetail.publisher;
        self.headerTimeLabel.text = [self.cosDetail.publish_time xd_yyyyMMddHHmmssStrToFriendDateStr];
        self.navigationItem.title = self.cosDetail.publisher;
    }
    // 背景图片
    self.headerSignLabel.text = self.cosDetail.publisher_sign;
    [self.headerBgImgView yy_setImageWithURL:[NSURL URLWithString:self.cosDetail.publisher_homepage_img_url] placeholder:[KABDefaultVarModel sharedInstance].skinDefaultImg];
    // 比赛相关
    CGFloat width = CGRectGetWidth([UIScreen mainScreen].bounds);
    CGFloat height = width * 153.0 / 375.0 + 116.0 + (self.cosDetail.is_competition ? 61.0 : 0.0);
    self.headerView.frame = CGRectMake(0, 0, width, height);
    self.tableView.tableHeaderView = self.headerView;
    self.headerRankBgView.hidden = !self.cosDetail.is_competition;
    self.headerRankBgViewHeight.constant = self.cosDetail.is_competition ? 61.0 : 0.0;
    self.headerVoteBtn.hidden = !self.cosDetail.is_competition;
    self.headerVoteBtn.selected = self.cosDetail.vote_info.is_vote;
    self.headerVoteBtn.backgroundColor = self.headerVoteBtn.selected ? [UIColor xd_colorWithHex:0xD8D8D8] : [UIColor xd_colorWithHex:KABGlobalColorRedBtnBorderColor];
    NSDictionary *attrsDic = @{NSForegroundColorAttributeName : [UIColor xd_colorWithHex:KABGlobalColorSettingFont],
                               NSFontAttributeName : [UIFont systemFontOfSize:12.0]};
    {
        NSString *totalRankStr = [NSString stringWithFormat:@"%zd", self.cosDetail.vote_info.ranking];
        NSString *rankStr = [NSString stringWithFormat:@"%@\n排名", totalRankStr];
        NSMutableAttributedString *mAStr = [[NSMutableAttributedString alloc] initWithString:rankStr];
        [mAStr addAttributes:attrsDic range:NSMakeRange(totalRankStr.length, rankStr.length - totalRankStr.length)];
        self.headerRankLabel.attributedText = mAStr;
    }
    {
        NSString *totalBallotStr = [NSString stringWithFormat:@"%zd", self.cosDetail.vote_info.ballot];
        NSString *ballotStr = [NSString stringWithFormat:@"%@\n票数", totalBallotStr];
        NSMutableAttributedString *mAStr = [[NSMutableAttributedString alloc] initWithString:ballotStr];
        [mAStr addAttributes:attrsDic range:NSMakeRange(totalBallotStr.length, ballotStr.length - totalBallotStr.length)];
        self.headerTicketCntLabel.attributedText = mAStr;
    }
    
    // 关注
    self.headerFollowBtn.selected = (self.cosDetail.follow_state & 0x01);
    self.headerFollowBtn.backgroundColor = self.headerFollowBtn.selected ? [UIColor whiteColor] : [UIColor xd_colorWithHex:KABGlobalColorTabBarItemColor];
    if (self.cosDetail.follow_state & 0x01) {
        NSString * title = @"已关注";
        if (self.cosDetail.follow_state & 0x02) {
            title = @"互粉";
        }
        [self.headerFollowBtn setTitle:title forState:UIControlStateSelected];
    }
    
    self.bCollectBtn.selected = self.cosDetail.is_collected;
    self.bPraiseBtn.selected = self.cosDetail.is_praise;
    
    [self.tableView reloadData];
    
//    if (self.scrollToComment) {
//        NSIndexPath *indexPath;
//        if (self.cosDetail.comment.count) {
//            indexPath = [NSIndexPath indexPathForRow:0 inSection:1];
//        } else {
//            indexPath = [NSIndexPath indexPathForRow:(self.cosDetail.cosplay_detail.count - 1) inSection:0];
//        }
//        [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
//    }
}

- (void)refreshCommentSection {
    // 尾部加载更多的显示
    if (self.cosDetail.totalLoad) {
        [self.tableView.mj_footer endRefreshingWithNoMoreData];
    } else {
        [self.tableView.mj_footer resetNoMoreData];
    }
    //
    [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:1] withRowAnimation:UITableViewRowAnimationAutomatic];
//    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:1];
//    [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
}

- (void)tableViewEndRefresh:(BOOL)isHeader {
    NSLog(@"停止刷新是否是头部---%zd", isHeader);
    if (isHeader) {
        [self.tableView.mj_header endRefreshing];
    } else {
        [self.tableView.mj_footer endRefreshing];
    }
}

- (void)tableViewRefresh:(id)sender {
    BOOL isHeader = [sender isKindOfClass:[MJRefreshHeader class]];
    [self requestCommentListWithHeader:isHeader];
}

#pragma mark - network request
- (void)requestCosplayDetail {
    MBProgressHUD *hud = [MBProgressHUD xd_showHUDAddedTo:self.view animated:YES];
    
    NSMutableDictionary *pars = [NSMutableDictionary dictionary];
    if (self.cosItem) {
        [pars setObject:@(self.cosItem.cosplayId) forKey:@"cosplay_id"];
    } else {
        [pars setObject:@(self.cosplay_id) forKey:@"cosplay_id"];
    }
    if ([KABModel sharedInstance].isLogin) {
        [pars setObject:@([KABModel sharedInstance].userInfo.uid) forKey:@"user_id"];
        [pars setObject:[KABModel sharedInstance].userInfo.access_token forKey:@"access_token"];
    }
    
    [[XDAFNetworking sharedInstance] GET:[ApiManager apiCosplay] parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"请求Cosplay详情返回：%@", responseObject);
        [hud hideAnimated:YES];
        if ([responseObject[KABGlobalJsonKeyErrCode] integerValue] == 200) {
            self.cosDetail = [KABCosplayDetail yy_modelWithDictionary:responseObject[KABGlobalJsonKeyResult]];
            [self refreshWholeView];
        } else {
            [MBProgressHUD showPromptWithAutoHideInView:self.view message:responseObject[KABGlobalJsonKeyMsg]];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"登录失败：%@", error);
        [hud hideAnimated:NO];
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"网络请求失败"];
    }];
}

- (void)requestFollowWithFollowerId:(NSInteger)followerId isFollow:(BOOL)isFollow {
    // 关注必须要登录
    if (![KABModel sharedInstance].isLogin) {
        [[NSNotificationCenter defaultCenter] postNotificationName:KABGlobalNotiUserTokenInvalid object:nil];
        return;
    }
    
    // 关注请求
    NSDictionary *pars = @{@"user_id" : @([KABModel sharedInstance].userInfo.uid),
                           @"access_token" : [KABModel sharedInstance].userInfo.access_token,
                           @"follower_id" : @(followerId),
                           @"is_follow" : isFollow ? @(1) : @(0)};
    [[XDAFNetworking sharedInstance] POST:[ApiManager apiFollow] parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"请求关注返回：%@", responseObject);
        if ([responseObject[KABGlobalJsonKeyErrCode] integerValue] == 200) {
            self.cosDetail.follow_state = ((self.cosDetail.follow_state & 0x02) | isFollow);
            [self refreshWholeView];
        } else {
            [MBProgressHUD showPromptWithAutoHideInView:self.view message:responseObject[KABGlobalJsonKeyMsg]];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"请求关注失败：%@", error);
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"网络请求失败"];
    }];
}
- (void)requestCosplayVote {
    // 投票必须要登录
    if (![KABModel sharedInstance].isLogin) {
        [[NSNotificationCenter defaultCenter] postNotificationName:KABGlobalNotiUserTokenInvalid object:nil];
        return;
    }
    
    // 关注请求
    NSDictionary *pars = @{@"user_id" : @([KABModel sharedInstance].userInfo.uid),
                           @"access_token" : [KABModel sharedInstance].userInfo.access_token,
                           @"cosplay_id" : @(self.cosDetail.cosplayId)};
    [[XDAFNetworking sharedInstance] POST:[ApiManager apiCosplayVote] parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"请求投票返回：%@", responseObject);
        if ([responseObject[KABGlobalJsonKeyErrCode] integerValue] == 200) {
            self.cosDetail.vote_info.is_vote = YES;
            self.cosDetail.vote_info.ballot++;
            [self refreshWholeView];
        } else {
            [MBProgressHUD showPromptWithAutoHideInView:self.view message:responseObject[KABGlobalJsonKeyMsg]];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"请求投票失败：%@", error);
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"网络请求失败"];
    }];
}
- (void)requestCommentListWithHeader:(BOOL)isHeader {
    NSInteger last_id = isHeader ? 0 : self.cosDetail.comment.lastObject.commentId;
    NSDictionary *pars = @{@"cosplay_id" : @(self.cosDetail.cosplayId),
                           @"last_id" : @(last_id),
                           @"size" : @(kRequestCommentSize)};
    NSLog(@"请求cos评论列表的参数：%@", pars);
    [[XDAFNetworking sharedInstance] GET:[ApiManager apiCosplayCommentList] parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"请求cos评论列表返回：%@", responseObject);
        [self tableViewEndRefresh:isHeader];
        if ([responseObject[KABGlobalJsonKeyErrCode] integerValue] == 200) {
            KABCosplayDetail *temp = [KABCosplayDetail yy_modelWithDictionary:responseObject[KABGlobalJsonKeyResult]];
            [self.cosDetail addMoreWithData:temp];
        } else {
            [MBProgressHUD showPromptWithAutoHideInView:self.view message:responseObject[KABGlobalJsonKeyMsg]];
        }
        [self refreshWholeView];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"请求cos评论列表失败：%@", error);
        [self tableViewEndRefresh:isHeader];
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"网络请求失败"];
    }];
}

- (void)requestCosPraiseWithCosId:(NSInteger)cosId isPraise:(BOOL)isPraise {
    // 点赞必须要登录
    if (![KABModel sharedInstance].isLogin) {
        [[NSNotificationCenter defaultCenter] postNotificationName:KABGlobalNotiUserTokenInvalid object:nil];
        return;
    }
    
    // 点赞请求
    NSDictionary *pars = @{@"user_id" : @([KABModel sharedInstance].userInfo.uid),
                           @"access_token" : [KABModel sharedInstance].userInfo.access_token,
                           @"cosplay_id" : @(cosId),
                           @"is_praise" : isPraise ? @(1) : @(0)};
    NSLog(@"点赞的请求%@", pars);
    [[XDAFNetworking sharedInstance] POST:[ApiManager apiCosplayPraise] parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"请求Cosplay点赞返回：%@", responseObject);
        if ([responseObject[KABGlobalJsonKeyErrCode] integerValue] == 200) {
            ;
        } else {
            [MBProgressHUD showPromptWithAutoHideInView:self.view message:responseObject[KABGlobalJsonKeyMsg]];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"请求Cosplay点赞失败：%@", error);
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"网络请求失败"];
    }];
}

- (void)requestCosCollectWithCosId:(NSInteger)cosId isCollected:(BOOL)isCollected {
    // 收藏必须要登录
    if (![KABModel sharedInstance].isLogin) {
        [[NSNotificationCenter defaultCenter] postNotificationName:KABGlobalNotiUserTokenInvalid object:nil];
        return;
    }
    
    // 收藏请求
    NSDictionary *pars = @{@"user_id" : @([KABModel sharedInstance].userInfo.uid),
                           @"access_token" : [KABModel sharedInstance].userInfo.access_token,
                           @"cosplay_id" : @(cosId),
                           @"is_collected" : isCollected ? @(1) : @(0)};
    
    [[XDAFNetworking sharedInstance] POST:[ApiManager apiCosplayCollected] parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"请求Cosplay收藏返回：%@", responseObject);
        if ([responseObject[KABGlobalJsonKeyErrCode] integerValue] == 200) {
            ;
        } else {
            [MBProgressHUD showPromptWithAutoHideInView:self.view message:responseObject[KABGlobalJsonKeyMsg]];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"请求Cosplay收藏失败：%@", error);
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"网络请求失败"];
    }];
}

// wId == -1 不传，单独评论
- (void)requestPublishCommentWithCosId:(NSInteger)cosId content:(NSString *)content replayWhichId:(NSInteger)wId {
    // 评论必须要登录
    if (![KABModel sharedInstance].isLogin) {
        [[NSNotificationCenter defaultCenter] postNotificationName:KABGlobalNotiUserTokenInvalid object:nil];
        return;
    }
    
    MBProgressHUD *hud = [MBProgressHUD xd_showHUDAddedTo:self.view animated:YES];
    
    NSMutableDictionary *pars = [NSMutableDictionary dictionary];
    [pars setObject:@([KABModel sharedInstance].userInfo.uid) forKey:@"user_id"];
    [pars setObject:[KABModel sharedInstance].userInfo.access_token forKey:@"access_token"];
    [pars setObject:@(cosId) forKey:@"cosplay_id"];
    [pars setObject:content forKey:@"content"];
    if (wId != -1) {
        [pars setObject:@(wId) forKey:@"reply_which_id"];
    }
    
    [[XDAFNetworking sharedInstance] POST:[ApiManager apiCosplayComment] parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [hud hideAnimated:YES];
        NSLog(@"请求Cosplay评论返回：%@", responseObject);
        if ([responseObject[KABGlobalJsonKeyErrCode] integerValue] == 200) {
            KABCosDetComItem *comment = [KABCosDetComItem yy_modelWithDictionary:responseObject[KABGlobalJsonKeyResult]];
            [self.cosDetail addNewComment:comment];
            [self refreshCommentSection];
            [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"评论成功！"];
        } else {
            [MBProgressHUD showPromptWithAutoHideInView:self.view message:responseObject[KABGlobalJsonKeyMsg]];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"请求Cosplay评论失败：%@", error);
        [hud hideAnimated:YES];
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"网络请求失败"];
    }];
}

#pragma mark - getters and setters
- (MJRefreshAutoNormalFooter *)mj_footer {
    if (!_mj_footer) {
        _mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(tableViewRefresh:)];
        _mj_footer.automaticallyRefresh = NO;
        _mj_footer.automaticallyHidden = YES;
    }
    return _mj_footer;
}

@end
